package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.GroupChatVoteDetail;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/1/5
 **/
public class GroupChatVoteDetailActivity extends BaseActivityImpl {
    @BindView(R.id.tv_is_multiple)
    TextView tvIsMultiple;
    @BindView(R.id.tv_subject)
    TextView tvSubject;
    @BindView(R.id.iv)
    ScaleImageView iv;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_options)
    LinearLayout llOptions;
    @BindView(R.id.tv_operate)
    TextView tvOperate;

    private HashSet<Integer> selectedIds = new HashSet<>();
    private int voteId;

    public static void show(Context context, int voteId) {
        Intent intent = new Intent(context, GroupChatVoteDetailActivity.class);
        intent.putExtra("voteId", voteId);
        context.startActivity(intent);
    }

    public static void show(Context context, int voteId, ActivityResultLauncher<Intent> launcher) {
        Intent intent = new Intent(context, GroupChatVoteDetailActivity.class);
        intent.putExtra("voteId", voteId);
        launcher.launch(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_group_chat_vote_detail;
    }

    @Override
    public String getTitleStr() {
        return "投票详情";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        voteId = getIntent().getIntExtra("voteId", -1);
        tvOperate.setEnabled(false);

        getGroupChatVoteDetail();
    }

    private void getGroupChatVoteDetail() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("vote_id", voteId);
        requestManager.request(requestManager.mMessageRetrofitService.getGroupChatVoteDetail(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<GroupChatVoteDetail>(mContext) {
                    @Override
                    public void onSuccess(GroupChatVoteDetail groupChatVoteDetail) {
                        super.onSuccess(groupChatVoteDetail);

                        if (groupChatVoteDetail.isVoted()) {
                            tvOperate.setEnabled(false);
                            tvOperate.setText("您已完成投票");
                        } else {
                            tvOperate.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    HashMap<String, Object> params = new HashMap<>();
                                    params.put("vote_id", voteId);
                                    params.put("ids", selectedIds);
                                    requestManager.request(requestManager.mMessageRetrofitService.GroupChatVoteVoting(RequestManager.getJsonRequestBody(params)),
                                            new BaseObserverImpl<Object>(mContext) {
                                                @Override
                                                public void onSuccess() {
                                                    super.onSuccess();
                                                    Intent intent = new Intent();
                                                    intent.putExtra("voteId", voteId);
                                                    setResult(RESULT_OK, intent);

                                                    getGroupChatVoteDetail();
                                                }
                                            });
                                }
                            });
                        }

                        tvSubject.setText(groupChatVoteDetail.getSubject());
                        GlideHelper.setCircleImage(mContext, groupChatVoteDetail.getUser_img(), iv, R.mipmap.icon_default_header_man);
                        tvName.setText(groupChatVoteDetail.getUsername());
                        tvSubject.setText(groupChatVoteDetail.getSubject());
                        try {
                            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(groupChatVoteDetail.getDatetime());

                            if (date != null) {
                                String time;
                                if (TimeUtils.isToday(date)) {
                                    time = new SimpleDateFormat("HH:mm").format(date);
                                } else {
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTimeInMillis(System.currentTimeMillis());
                                    int x = calendar.get(Calendar.DAY_OF_YEAR);

                                    calendar.setTimeInMillis(date.getTime());
                                    int y = calendar.get(Calendar.DAY_OF_YEAR);

                                    if (x - y == 1) {
                                        time = "昨天 " + new SimpleDateFormat("HH:mm").format(date);
                                    } else {
                                        time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                                    }
                                }
                                tvTime.setText(time + "发布");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        GradientDrawable bg = new GradientDrawable();
                        bg.setCornerRadius(SizeUtils.dp2px(5));
                        bg.setColor(Color.parseColor("#EBF1FF"));
                        tvIsMultiple.setBackground(bg);
                        tvIsMultiple.setText((groupChatVoteDetail.isIs_multiple() ? "多选" : "单选") + "，匿名");

                        int dp12 = SizeUtils.dp2px(12);
                        if (groupChatVoteDetail.isVoted()) {
                            if (llOptions.getChildCount() > 0) {
                                llOptions.removeAllViews();
                            }
                            for (GroupChatVoteDetail.Option option : groupChatVoteDetail.getOptions()) {
                                LinearLayout llOption = new LinearLayout(mContext);
                                llOption.setGravity(Gravity.CENTER_VERTICAL);
                                llOption.setOrientation(LinearLayout.HORIZONTAL);
                                llOption.setPadding(dp12, dp12, dp12, dp12);
                                if (option.isIs_select()) {
                                    llOption.setBackgroundResource(R.drawable.shape_bg_corner_green_light_stroke_green);
                                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                    layoutParams.setMargins(0, dp12, 0, 0);
                                    llOption.setLayoutParams(layoutParams);
                                }

                                TextView tvOption = new TextView(mContext);
                                tvOption.setTextAppearance(R.style.NormalTextView);
                                tvOption.setText(option.getContent());
                                Drawable drawable = ContextCompat.getDrawable(mContext, option.isIs_select() ? R.mipmap.icon_checked_oval : R.mipmap.icon_unchecked_oval);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                tvOption.setCompoundDrawablePadding(dp12);
                                tvOption.setCompoundDrawables(drawable, null, null, null);

                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
                                layoutParams.weight = 1;

                                llOption.addView(tvOption, layoutParams);

                                TextView tvSelectCount = new TextView(mContext);
                                tvSelectCount.setTextAppearance(R.style.NormalTextView);
                                tvSelectCount.setText(option.getNumber() + "票");
                                if (option.isIs_select()) {
                                    tvSelectCount.setTextColor(ContextCompat.getColor(mContext, R.color.green_theme));
                                }

                                llOption.addView(tvSelectCount);

                                llOptions.addView(llOption);
                            }
                        } else {
                            for (GroupChatVoteDetail.Option option : groupChatVoteDetail.getOptions()) {
                                CheckBox cb = new CheckBox(mContext);
                                cb.setId(option.getId());
                                cb.setPadding(dp12, dp12, dp12, dp12);
                                cb.setText(option.getContent());
                                cb.setTextAppearance(R.style.NormalTextView);
                                Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.selector_checked_oval);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                cb.setCompoundDrawables(drawable, null, null, null);
                                cb.setCompoundDrawablePadding(SizeUtils.dp2px(12));
                                cb.setButtonDrawable(null);
                                cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                        if (isChecked) {
                                            selectedIds.add(buttonView.getId());
                                        } else {
                                            selectedIds.remove(buttonView.getId());
                                        }

                                        tvOperate.setEnabled(selectedIds.size() > 0);
                                    }
                                });
//                                ContextCompat.getDrawable(mContext, R.drawable.selector_checked_oval);
                                cb.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        if (!groupChatVoteDetail.isVoted()) {
                                            if (!groupChatVoteDetail.isIs_multiple()) {
                                                if (((CheckBox) v).isChecked()) {
                                                    for (int i = 0; i < llOptions.getChildCount(); i++) {
                                                        CheckBox cb = (CheckBox) llOptions.getChildAt(i);
                                                        if (cb.isChecked()) {
                                                            if (cb.getId() != v.getId()) {
                                                                cb.setChecked(false);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                                llOptions.addView(cb);
                            }
                        }
                    }
                });
    }
}





































